package gold.digger;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC27 {

    public int removeElement(int[] nums, int val) {
        int endPos = nums.length - 1;
        while (endPos >= 0 && nums[endPos] == val) {
            --endPos;
        }

        for (int i = 0; i <= endPos; ) {
            if (nums[i] == val && nums[endPos] != val) {
                swapEle(nums, i++, endPos--);
            } else if (nums[i] == val && nums[endPos] == val) {
                --endPos;
            } else {
                ++i;
            }
        }

        return endPos + 1;
    }

    private void swapEle(int arr[], int posA, int posB) {
        int temp = arr[posA];
        arr[posA] = arr[posB];
        arr[posB] = temp;
    }

    public static void main(String[] args) {
        LC27 an = new LC27();
        int[] nums = {0, 1, 2, 2, 3, 0, 4, 2};
        System.out.println(an.removeElement(nums, 2));
    }
}
